import axios from "axios";
import qs from "qs";
import store from "@index/store/index";
// import { Message } from 'element-ui'

// const serverURL = "http://nanhai.com.cn"
// 122.224.69.204
// const serverURL = "http://122.224.69.204"

const service = axios.create({
	// baseURL: serverURL,
	headers: {
		post: {
			"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
		},
	},
	timeout: 10000,
});

//这里是取消重复请求的函数
const pending = new Map();
/**
 * 添加请求
 * @param {Object} config
 */
const addPending = config => {
	const url = [config.method, config.url, qs.stringify(config.params), qs.stringify(config.data)].join("&");
	config.cancelToken =
		config.cancelToken ||
		new axios.CancelToken(cancel => {
			if (!pending.has(url)) {
				// 如果 pending 中不存在当前请求，则添加进去
				pending.set(url, cancel);
			}
		});
};
/**
 * 移除请求
 * @param {Object} config
 */
const removePending = config => {
	const url = [config.method, config.url, qs.stringify(config.params), qs.stringify(config.data)].join("&");
	if (pending.has(url)) {
		// 如果在 pending 中存在当前请求标识，需要取消当前请求，并且移除
		const cancel = pending.get(url);
		cancel(url);
		pending.delete(url);
	}
};

service.interceptors.request.use(
	config => {
		// console.log(config)
		// Do something before request is sent
		removePending(config); // 在请求开始前，对之前的请求做检查取消操作
		addPending(config); // 将当前请求添加到 pending 中
		//再url后面加上当前时间戳（需要的话）
		if (config.url.indexOf("?") !== -1) {
			config.url += `&t=${new Date().getTime()}`;
		} else {
			config.url += `?t=${new Date().getTime()}`;
		}

		//对传入数据进行格式转化
		config.transformRequest = [
			data => {
				if (data instanceof FormData) {
					return data;
				} else {
					return qs.stringify(data, {
						allowDots: true,
					});
				}
			},
		];
		//项目中的token，名称不匹配后期修改
		let token;
		if (localStorage.getItem('userInfo')) {
			token = JSON.parse(localStorage.getItem('userInfo')).token
		}
		if (store.state.UserLevel.userInfo) {
			token = store.state.UserLevel.userInfo.token;
		}
		if (token) {
			config.headers.token = `${token}`;
		}
		return config;
	},
	error => {
		// Do something with request error
		return Promise.reject(error);
	}
);

service.interceptors.response.use(
	response => {
		removePending(response);
		// Do something before response is sent
		const res = response.data;
		//这里如果接口有登录状态，可以在此处进行登录状态的页面跳转
		return res;
	},
	error => {
		return Promise.reject(error);
	}
);

export default service;